package com.huibeili.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huibeili.common.core.domain.AjaxResult;
import com.huibeili.common.utils.CustomHttpUtils;
import com.huibeili.common.utils.ThreadTask;
import com.huibeili.common.utils.WeChatAppletUtils;
import com.huibeili.common.utils.bean.WechatSetting;
import com.huibeili.member.service.WxAppletAccessTokenService;
import com.huibeili.setting.bean.WechatPaySet;
import com.huibeili.setting.service.ILsPaySettingService;
import com.huibeili.sms.domain.TLiveInfo;
import com.huibeili.sms.service.ITLiveInfoService;
import com.huibeili.sms.service.LivePlayerService;
import com.huibeili.sms.vo.LivePlayerRequest;
import com.huibeili.sms.vo.LivePlayerResponse;
import com.huibeili.sms.vo.RoomInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 小程序直播列表服务接口实现类
 *
 * @author Caizize huibeili on 2020/4/27
 */
@Service
@Slf4j
public class LivePlayerServiceImpl implements LivePlayerService {

    /**
     * 注入支付设置服务
     */
    @Autowired
    private ILsPaySettingService paySetService;

    /**
     * 注入微信小程序access_token服务接口
     */
    @Autowired
    private WxAppletAccessTokenService wxAppletAccessTokenService;
    @Autowired
    private ITLiveInfoService liveInfoService;

    /**
     * 获取小程序直播房间列表
     *
     * @param livePlayerRequest 小程序直播列表请求实体
     * @return 小程序直播房间列表
     */
    @Override
    public AjaxResult queryLivePlayerList(LivePlayerRequest livePlayerRequest) {
        log.debug("queryLivePlayerList and livePlayerRequest:{} ", livePlayerRequest);
        if (Objects.isNull(livePlayerRequest)) {
            //    return Collections.emptyList();
        }
        LivePlayerResponse livePlayerResponse = new LivePlayerResponse();
        try {
            // 获取微信小程序支付设置
            WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(0).getWechatAppletPaySet();
            WechatSetting wechatSetting = new WechatSetting();
            wechatSetting.setAppId(wechatAppletPaySet.getAppId());
            wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
            // 设置获取微信小程序码接口调用凭证
            String accessToken = wxAppletAccessTokenService.getWxAppletAccessToken(wechatSetting);
            if (StringUtils.isEmpty(accessToken)) {
                log.error("queryLivePlayerList fail due to accessToken is null");
                return AjaxResult.error();
            }
            // 获取微信小程序直播列表地址
            String getWeChatAppletLivePlayerListUrl = WeChatAppletUtils.getWeChatAppletLivePlayerListUrl(accessToken);
            if (StringUtils.isEmpty(getWeChatAppletLivePlayerListUrl)) {
                log.error("queryLivePlayerList fail due to getWeChatAppletLivePlayerListUrl is null");
                return AjaxResult.error();
            }
            // 获取请求返回信息
            String liveResponseString = CustomHttpUtils.postJson(getWeChatAppletLivePlayerListUrl, JSON.toJSONString(livePlayerRequest));
            if (Objects.isNull(liveResponseString)) {
                log.error("queryLivePlayerList fail due to http post response null");
                return AjaxResult.error();
            }
            livePlayerResponse = JSONObject.parseObject(liveResponseString, LivePlayerResponse.class);
            // 判断是否正确返回信息
            if (livePlayerResponse.getErrcode() != 0) {
                log.error("queryLivePlayerList fail due to errmsg :{}", livePlayerResponse.getErrmsg());
                return AjaxResult.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        if (CollectionUtils.isEmpty(livePlayerResponse.getRoom_info())) {
            return AjaxResult.error();
        }
        LivePlayerResponse finalLivePlayerResponse = livePlayerResponse;
        ThreadTask.getInstance().addTask(() -> {
            synLiveInfo(finalLivePlayerResponse.getRoom_info());
        });
        return AjaxResult.success(livePlayerResponse.getRoom_info().stream().peek(RoomInfo::formatTime).collect(Collectors.toList()));
    }

    public void synLiveInfo(List<RoomInfo> roomInfoList) {
        for (RoomInfo info : roomInfoList) {
            TLiveInfo oldLiveInfo = liveInfoService.selectTLiveInfoById(info.getRoomid());
            if (oldLiveInfo == null) {
                TLiveInfo liveInfo = new TLiveInfo();
                liveInfo.setAnchorName(info.getAnchor_name());
                liveInfo.setCoverImg(info.getCover_img());
                liveInfo.setEndTime(info.getEnd_time());
                liveInfo.setName(info.getName());
                liveInfo.setLiveStatus(info.getLive_status());
                liveInfo.setShareImg(info.getShare_img());
                liveInfo.setRoomid(info.getRoomid());
                liveInfo.setCreateTime(new Date());
                liveInfoService.insertTLiveInfo(liveInfo);
            } else if (oldLiveInfo != null && (oldLiveInfo.getLiveStatus() == 102 || oldLiveInfo.getLiveStatus() == 101 || oldLiveInfo.getLiveStatus() == 105)
                    && info.getLive_status() > 102) {
                oldLiveInfo.setLiveStatus(info.getLive_status());
                liveInfoService.updateTLiveInfo(oldLiveInfo);
            }
        }
    }

}
